import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/http/models/HotIdsModel.dart';

import '../../../common/action/index.dart';
import '../../../common/global/global.dart';
import '../../../http/apis/common.dart';
import '../../../http/models/newanchorModel.dart';
import '../../../states/states_model/user.dart';
import '../../../widgets/easyRefreshWidget.dart';
import '../../../widgets/tipsDialog.dart';

class NewPeople extends StatefulWidget {
  NewPeople({Key key}) : super(key: key);

  @override
  _NewPeopleState createState() => _NewPeopleState();
}

class _NewPeopleState extends State<NewPeople> {
  int _page = 0;
  final int _limit = 8;

  List<HotIdsModel> ids = [];

  List<NewanchorModel> list = [];

  List<int> get pageIds {
    if (_page > ids.length - 1) return [];
    if (_page + _limit > ids.length - 1 && _page < ids.length - 1) {
      return ids.sublist(_page, ids.length).map((e) => e.id).toList();
    }
    return ids.sublist(_page, _page + _limit).map((e) => e.id).toList();
  }

  List<NewanchorModel> get anchorList {
    final arr = ids.where((item) {
      for (var anchor in list) {
        if (anchor.memberToken == item.memberToken) {
          return true;
        }
      }
      return false;
    }).map<NewanchorModel>((item) {
      NewanchorModel info;
      for (var anchor in list) {
        if (anchor.memberToken == item.memberToken) {
          anchor.online = item.online;
          info = anchor;
        }
      }
      return info;
    }).toList();
    return arr;
  }

  @override
  void initState() {
    super.initState();

    CommonApis.newanchorIds().then((value) {
      ids = value;
      CommonApis.newanchorPage(pageIds).then((res) {
        list = res;
        setState(() {});
        if (pageIds.length > 0) _page += _limit;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      header: EasyRefreshSetting.header,
      footer: EasyRefreshSetting.footer,
      onRefresh: () async {
        _page = 0;
        list = [];
        CommonApis.newanchorIds().then((value) {
          ids = value;
          CommonApis.newanchorPage(pageIds).then((res) {
            list = res;
            setState(() {});
            if (pageIds.length > 0) _page += _limit;
          });
        });
      },
      onLoad: () async {
        CommonApis.newanchorPage(pageIds).then((res) {
          list.addAll(res);
          setState(() {});
          if (pageIds.length > 0) _page += _limit;
        });
      },
      child: SingleChildScrollView(
        padding: EdgeInsets.only(bottom: px(16)),
        child: Builder(
          builder: (context) {
            List<Widget> arr = List.generate(
              anchorList.length,
              (i) => GestureDetector(
                onTap: () {
                  final user = Provide.value<UserState>(context);
                  final info = user.info;
                  final isLogin = info != null;
                  if (isLogin) {
                    goPage(
                      context,
                      '/anchorInfo',
                      param: {'token': anchorList[i].memberToken},
                    );
                  } else {
                    TipsDialog.login(
                      context,
                      () {
                        goPage(context, '/phoneLogin');
                      },
                    );
                  }
                },
                child: Container(
                  width: px(343),
                  height: px(456),
                  margin: EdgeInsets.only(top: px(16)),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(px(16)),
                    child: Stack(
                      children: [
                        SizedBox(
                          width: double.infinity,
                          height: px(600),
                          child: CachedNetworkImage(
                            imageUrl:
                                "${anchorList[i].firstimg}?imageView2/2/w/343",
                            fit: BoxFit.cover,
                            errorWidget: (context, url, error) {
                              return Config.errorNetImage;
                            },
                          ),
                        ),
                        Positioned(
                          top: px(20),
                          left: px(24),
                          child: _Price(anchorList[i]),
                        ),
                        Positioned(
                          top: px(20),
                          right: px(24),
                          child: _OnlineStatus(anchorList[i]),
                        ),
                        Positioned(
                          bottom: px(20),
                          left: px(25),
                          child: _Info(anchorList[i]),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
            if (anchorList.length % 2 != 0) {
              arr.add(Container(
                width: px(343),
                height: px(456),
                margin: EdgeInsets.only(top: px(16)),
              ));
            }
            return Wrap(
              alignment: WrapAlignment.spaceEvenly,
              children: arr,
            );
          },
        ),
      ),
    );
  }
}

class _OnlineStatus extends StatelessWidget {
  final NewanchorModel info;

  const _OnlineStatus(this.info, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: px(48),
      padding: EdgeInsets.symmetric(horizontal: px(18)),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(px(24))),
        color: col("04040f").withOpacity(.4),
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: px(12),
            height: px(12),
            margin: EdgeInsets.only(right: px(8)),
            decoration: BoxDecoration(
              color: CommonAction.checkAnchorStatus(
                info.disturb,
                info.online,
              ).color,
              borderRadius: BorderRadius.circular(px(6)),
            ),
          ),
          Text(
            "${CommonAction.checkAnchorStatus(
              info.disturb,
              info.online,
            ).text}",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(24),
            ),
          ),
        ],
      ),
    );
  }
}

class _Info extends StatelessWidget {
  final NewanchorModel info;

  const _Info(this.info, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            info.memberNickname,
            style: TextStyle(
              color: Colors.white,
              fontSize: px(32),
              fontWeight: FontWeight.bold,
              shadows: [
                Shadow(
                  color: Colors.black26,
                  blurRadius: 1,
                  offset: Offset(1, 1),
                ),
              ],
            ),
          ),
          SizedBox(height: px(10)),
          Container(
            width: px(300),
            child: Text(
              info.anchorSign,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: Colors.white.withOpacity(.9),
                fontSize: px(24),
                shadows: [
                  Shadow(
                    color: Colors.black26,
                    blurRadius: 1,
                    offset: Offset(1, 1),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _Price extends StatelessWidget {
  final NewanchorModel info;

  const _Price(this.info, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: px(48),
      padding: EdgeInsets.symmetric(horizontal: px(10)),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(px(24))),
        gradient: LinearGradient(
          colors: [
            col("ffda2a"),
            col("f99705"),
          ],
        ),
      ),
      child: Row(
        children: [
          Image.asset(
            "assets/images/icon/star.png",
            width: px(30),
            height: px(30),
          ),
          SizedBox(width: px(5)),
          Text(
            "${info.timePrice}金币/分钟",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(24),
            ),
          ),
        ],
      ),
    );
  }
}
